#include "iconworker.h"
#include "iconmanager.h"

#include <QDir>
#include <QPixmap>
#include <QStandardPaths>
#include <httpclient.h>

IconWorker::IconWorker(IconManager *manager)
    : QObject(),
    manager(manager)
{

}

void IconWorker::slotRequest(QString url, QString objectName)
{
    qDebug() << "------" << objectName;
    QPixmap pixmap = getAppCachePixmap(objectName);
    if (pixmap.isNull()) {
        Response resp = HttpClient::instance().get(url);
        QByteArray data = resp.content();
        pixmap = QPixmap::fromImage(QImage::fromData(data));
        pixmap.setDevicePixelRatio(manager->dpr());

        if (pixmap.isNull() == false) {
            setAppCachePixmap(objectName, pixmap);
        }
    }
    emit manager->onRequested(pixmap, objectName);
}

void IconWorker::slotRequestList(QVariantList list)
{
    for (int i = 0; i < list.count(); ++i) {
        auto v = list.at(i);
        slotRequest(v.toMap().value("icon").toString(), v.toMap().value("appId").toString());
    }
}

void IconWorker::slotRequestJson(QString json)
{
    QThread::sleep(1);
    slotRequestList(Response(0, json).toList());
}

QString IconWorker::configDir()
{
    QString configDir = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
    return configDir + QDir::separator();
}

QString IconWorker::appConfigDir()
{
    QString path = configDir() + "linglong-apps-analyzer";
    return path + QDir::separator();
}

QString IconWorker::cacheDir()
{
    QString cacheDir = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
    return cacheDir + QDir::separator();
}

QString IconWorker::appCacheDir()
{
    QString path = cacheDir() + "linglong-apps-analyzer";
    return path + QDir::separator();
}

QPixmap IconWorker::getAppCachePixmap(const QString &appId)
{
    QDir dir;
    if (dir.exists(appCacheDir()) == false) {
        return QPixmap();
    }

    QString path = appConfigDir() + appId + ".png";
    QPixmap pixmap(path);
    pixmap.setDevicePixelRatio(manager->dpr());
    return pixmap;
}

void IconWorker::setAppCachePixmap(const QString &appId, QPixmap pixmap)
{
    if (pixmap.isNull()) {
        return;
    }

    QDir dir;
    if (dir.exists(appCacheDir()) == false) {
        if (dir.mkdir(appCacheDir()) == false) {
            return;
        }
    }

    QString path = appCacheDir() + appId + ".png";

    pixmap.save(path);
}
